import React, {Fragment} from 'react';
import {connect} from 'dva'
import {Page,Loader} from 'components'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import {Row,Col,Form,Radio,Button,Steps,Icon,Card,Popover,Input,message,Modal,Select} from 'antd'
import LwjSelect from 'components/LwjSelect/LwjSelect'
import PositionSelect  from './PositionSelect'
import style from './index.less'
import AddAddress from './AddAddress'
import LwjTable from 'components/LwjTable/LwjTable'
import {Link} from 'dva/router'
import moment from 'moment';

const Step = Steps.Step;
const Option = Select.Option;
const cartcaluates = ({location, dispatch, cartcaluate, app, loading}) => {

  const {
    activeTab,
    modalVisible,
    address,
    isEdit,
    addressList,
    selectedShippingMethod,
    products,
    comment,
    totalChannelPrice,
    totalNumber,
    storeList,
    selectedStoreId,
    accountBalance,
    paymentType,
    salesOrderId
  } = cartcaluate;

  const { user } = app;

  // 面包屑
  const breadcrumbList = [
    {
      title: '分销市场',
    }, {
      title: '分销市场',
      href: '/salesmarket/salesmarket'
    }, {
      title: '购物车',
      href: '/salesmarket/cartList'
    }, {
      title: '结算'
    }
  ];

  const steps = [{
    title: '购物车',
    content: 'First-content',
  }, {
    title: '确认订单',
    content: 'Second-content',
  }, {
    title: '成功',
    content: 'Last-content',
  }];
  

  const gridStyle = {
    width: '25%',
    textAlign: 'center'
  };

  //地址配置项
  const positionSelectProps={
    items: addressList,
    itemInch:{
      width:270,
      height:'auto',
      lineHeight:'30px'
    },
    //编辑地址
    deleteAddress(){
      dispatch({
        type: 'cartcaluate/setAddressList',
        addressList: []
      })
    },
    //删除地址
    updateAddress(address){
      dispatch({
        type: 'cartcaluate/showModal',
        modalVisible: true,
        address: address
      })
    }
  }

  //打开新增或编辑弹窗
  const addAddress=(isEdit, address)=>{
    if(!addressList || (addressList && addressList.length == 0)){
      dispatch({
        type: 'cartcaluate/showModal',
        modalVisible: true,
        address: address,
        idEdit: isEdit
      })
    }
  }

  // 新增窗口
  const addprops = {
    title: '合同信息',
    visible: modalVisible,
    onOk: (address) => {
      dispatch({
        type: 'cartcaluate/setAddressList',
        addressList: [address]
      })
      dispatch({
        type: 'cartcaluate/hideModal'
      })
    },
    confirmLoading: false,
    onCancel: () => {
      dispatch({
        type: 'cartcaluate/hideModal'
      })
    },
    destroyOnClose: true,
    width: 1000,
    dispatch,
  }

 // 配送提示内容
  const content = (
    <div>
      <p>自提：物流商品从发货地送到买家城市后，买家自行到物流点提货。</p>
      <p>送货上门：由丽维家负责配送、并由专业人员上门安装。</p>
    </div>
  );

  //配送方式
  const selectProps={
    items: [{
      value:'物流点自提',
      id:'TAKE_BY_SELF',
    }, {
      value:'送货上门安装',
      id:'DOOR_TO_DOOR'
    }],
    selected: selectedShippingMethod,
    itemInch: {
      width:110,
      height:30,
      lineHeight:'30px'
    },
    onSelect(value){
      dispatch({
        type: 'cartcaluate/setShippingMethod',
        id: value.id
      })
    }
  }
  
  //商品列表
  const listProps = {
    dataSource: products,
    loading: loading.effects['contractInProduction/query'],
    pageChangeAction: 'contractInProduction/query',
    dispatch,
    location,
    locale:{
      emptyText:"您的商品详情是空的哟~"
    }
  }

  const goPayment = (type) => {
    if(!addressList || (addressList && addressList.length == 0)){
      message.error("请填写合同信息");
      return;
    }
    if(!products || (products && products.length == 0)){
      message.error("没有商品待支付");
      return;
    }
    if(totalChannelPrice == '0' || totalChannelPrice == '0.00'){
      message.error("所购商品价格价格有误,请核实后提交");
      return;
    }
    let address = addressList[0];
    let goodsSnapshots = products.map((value) => {
      return{
        goodsId: value.commodityId,
        skuId: value.commodityId,
        name: value.commodityName,
        brandName: value.brandName,
        price: value.price,
        channelPrice: value.channelPrice,
        coverPath: value.coverPath,
        number: value.number
      }
    })
    dispatch({
      type: ( type == 'ON_LINE' ? 'cartcaluate/queryOnlinePayment' : 'cartcaluate/queryAccountPayment'),
      queryParam: {
        orderContractAt: moment(address.orderContractAt).valueOf(),
        installContractAt: moment(address.installContractAt).valueOf(),
        contactName: address.contactName,
        contactPhone: address.contactPhone,
        provinceId: address.consigneeRegion[0],
        cityId: address.consigneeRegion[1],
        districtId: address.consigneeRegion[2],
        address: address.consigneeAddress,
        consigneeName: address.consigneeName,
        consigneePhoneNum: address.consigneePhoneNum,
        customerName: address.customerName,
        customerPhoneNum: address.customerPhoneNum,
        contractType: address.contractType,
        goodsSnapshots: goodsSnapshots,
        quantity: totalNumber,
        amountInPrice: totalChannelPrice,
        amountInChannelPrice: totalChannelPrice,
        description: comment,
        salesDistributorId: selectedStoreId,
        salesOrderId: salesOrderId,
        payType: type,
        sourceSystem: ( salesOrderId ? 'NULL' : 'SAlES_MARKET')
      }
    })
    dispatch({
      type: 'cartcaluate/setPaymentType',
      paymentType: type
    })
  }

  const productsColumns = [
    {
      title: '商品名称',
      dataIndex: 'productInfo',
      key: 'productInfo',
      width: '40%',
      align:'left',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
            <img src={record.coverPath} className={style.pitemImg}></img>
            <p className={style.pp}>{record.commodityName}</p>
          </div>
        </div>
      )
    }, {
      title: '单价（元）',
      dataIndex: 'channelPrice',
      key: 'channelPrice',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
             {record.channelPrice}
          </div>
        </div>
      )
    }, 
    {
      title: '数量',
      dataIndex: 'number',
      key: 'number',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
             {record.number}
          </div>
        </div>
      )
    },{
      title: '实付（元）',
      dataIndex: 'totalChannelPrice',
      key: 'totalChannelPrice',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
             {record.totalChannelPrice}
          </div>
        </div>
      )
    }, 
  ]

  const onCommentChange = (e) => {
    dispatch({
      type: 'cartcaluate/setComment',
      comment: e.target.value
    })
  }

  const handleStoreChange = (selectedStoreId) => {
    dispatch({
      type: 'cartcaluate/setSelectedStoreId',
      selectedStoreId
    })
  }

  const confirmGoPayment = () => {
    if(!addressList || (addressList && addressList.length == 0)){
      message.error("请填写合同信息");
      return;
    }
    if(!products || (products && products.length == 0)){
      message.error("没有商品待支付");
      return;
    }
    if(totalChannelPrice == '0' || totalChannelPrice == '0.00'){
      message.error("所购商品价格价格有误,请核实后提交");
      return;
    }
    Modal.confirm({
      title: '确认支付?',
      content: '应付金额：'+totalChannelPrice+'元 (账户余额：'+accountBalance+'元)',
      onOk() {
        goPayment("BALANCE");
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const goBack = () => {
    dispatch({
      type: (salesOrderId ? 'cartcaluate/backOrderCart' : 'cartcaluate/backSalesmarketCart')
    })
  }

  return (
    <PageHeaderLayout title="结算页" breadcrumbList={breadcrumbList}>
 
      <AddAddress {...addprops} item={address} user={user}/>

      <div className={style.main}>
        <Steps current={activeTab} className={style.step}>
          {steps.map(item => <Step key={item.title} title={item.title} />)}
        </Steps>

        <div style={{display: (activeTab == '1' ? 'block' : 'none')}}>

          {/*<div style={{marginTop:'20px'}}>
            <Card title="门店信息" bordered={false}>
              <Select
                defaultValue={selectedStoreId}
                style={{ width: 200 }}
                onChange={handleStoreChange}
              >
                <Option key='-1'>请选择</Option>
                {storeList.map((store) => <Option key={store.id}>{store.name}</Option>)}
              </Select>
            </Card>
          </div>*/}

          <div style={{marginTop:'20px'}}>
            <Card title="合同信息" bordered={false}  extra={addressList && addressList.length > 0 ? null : <a href="javascript:;" onClick={() => addAddress(true, {})} >新增合同信息</a>}>
              <PositionSelect {...positionSelectProps}/>
            </Card>
          </div>

          <div style={{marginTop:'20px'}}>
            <Card title="商品信息" bordered={false}  extra={<a onClick={() => goBack()}>返回购物车</a>}>
              <LwjTable {...listProps} columns={productsColumns} pagination={false}/>
            </Card>
          </div>
                
          {/*<div style={{marginTop:'2px'}}>
            <p className={style.peisong}>配送方式
              <Popover content={content} title="Title">
                <Icon className={style.ico} type="question-circle" theme="outlined" />
              </Popover>
            </p>
            <LwjSelect style={{paddingLeft:'32px'}} {...selectProps}/>
          </div>*/}

          <div style={{ marginTop:'2px'}} className={style.priceCon}>
            <Row type="flex" justify="space-between" align="bottom">
              <Col span={8}>
                <Row  className={style.leftWord}>
                  <Col span={24}>下单备注：</Col>
                </Row>
                <Row className={style.leftWord} >
                  <Col span={24}>
                    <Input maxLength={500} placeholder="选填：对本次交易的说明" onChange={onCommentChange}/>
                  </Col>
                </Row>
              </Col>
              <Col span={8} offset={8}>
                <Row className={style.rightWord}>
                  <Col span={12}>商品数量（件）：</Col>
                  <Col span={12} className={style.rrprice}>{totalNumber}件</Col>
                </Row>
                <Row className={style.rightWord}>
                  <Col span={12}>商品总金额（元）：</Col>
                  <Col span={12} className={style.rrprice}>￥{totalChannelPrice}</Col>
                </Row>
                <Row className={style.rightWord}>
                  <Col span={12}>金额（元）：</Col>
                  <Col span={12} className={style.rrprice2}>￥{totalChannelPrice}</Col>
                </Row>
              </Col>
            </Row>
            <Row className={style.zhifu}>
              <Col span={6} offset={18}>
                <Button className={style.zhifubutton} type='primary' onClick={confirmGoPayment}>余额支付</Button>
                <Button className={style.zhifubutton} type='danger' onClick={() => goPayment('ON_LINE')}>线上支付</Button>
              </Col>
            </Row>
          </div>
          <Loader spinning={loading.effects['cartcaluate/queryAccountPayment']} />
          <Loader spinning={loading.effects['cartcaluate/queryOnlinePayment']} />
        </div>
        <div style={{marginTop:'20px', textAlign: 'center', fontSize: '16px', padding: '50px 20px', color: '#33bdb8', backgroundColor: "#fff", display: (activeTab == '2' ? 'block' : 'none')}}>
          <Icon type="check-circle" theme="outlined" style={{marginRight: '10px'}} />
          { paymentType == 'BALANCE' ? '订单已支付成功，等待设计师处理。' : '您的订单在2小时内未支付将被取消，请尽快完成支付。'}
        </div>
      </div>
    </PageHeaderLayout>
  )
};

export default connect(({cartcaluate, app, loading}) => ({cartcaluate, app, loading}))(cartcaluates)
